//
//  MNDCreditorHRdetailViewController.m
//  minidai
//
//  Created by 谭谭伟 on 2017/6/20.
//  Copyright © 2017年 迷你金服. All rights reserved.
//

#import "MNDCreditorHRdetailViewController.h"
#import "WMPanGestureRecognizer.h"
#import "MNDFinaceDetailModel.h"
#import "MNDFinanceDescribleViewController.h"
#import "MNDFinanceRecordViewController.h"
#import "MNDTenderInfoViewController.h"
#import "MNDTransferRecordViewController.h"
#import "MNDInvestModel.h"
#import "MNDFinanceViewController.h"
#import "MNDLoginUserModel.h"
#import "MNDFinanceAlertViewController.h"
#import "MNDCreditorInvestViewController.h"
#import "MNDRiskAssessWebViewController.h"

@interface MNDCreditorHRdetailViewController ()
//借款标题
@property (weak, nonatomic) IBOutlet UILabel *borrowTitleLabel;
//借款年利率
@property (weak, nonatomic) IBOutlet UILabel *borrowYearAprLabel;
//借款期限
@property (weak, nonatomic) IBOutlet UILabel *borrowDeadlineLabel;
//转让本金
@property (weak, nonatomic) IBOutlet UILabel *creditorPrincipalLabel;
//转让价格
@property (weak, nonatomic) IBOutlet UILabel *creditorWorthLabel;
//债权余额
@property (weak, nonatomic) IBOutlet UILabel *creditorAmountMoneyLabel;
//最低可投
@property (weak, nonatomic) IBOutlet UILabel *leastTenderMoneyLabel;
//进度
@property (weak, nonatomic) IBOutlet UILabel *progressLabel;
//借款总额
@property (weak, nonatomic) IBOutlet UILabel *borrowMoneyLabel;
//回款方式
@property (weak, nonatomic) IBOutlet UILabel *backWayLabel;
//起息日期
@property (weak, nonatomic) IBOutlet UILabel *borrowStartDateLabel;
//发布时间
@property (weak, nonatomic) IBOutlet UILabel *borrowReleaseTimeLabel;
@property (weak, nonatomic) IBOutlet UIView *topScrollView;
@property (nonatomic, strong) WMPanGestureRecognizer *panGesture;
@property (nonatomic, assign) CGPoint lastPoint;
@property (nonatomic,strong) MNDFinaceDetailModel *detaiModel;
//投资数据
@property (strong, nonatomic) MNDInvestModel *investModel;
@property (strong,nonatomic) UIButton *investButton;

@property (strong ,nonatomic) MNDFinanceDescribleViewController *describleVC;
@property (strong ,nonatomic) MNDFinanceRecordViewController *financeRecordVC;
@property (strong ,nonatomic) MNDTenderInfoViewController *tenderInfoVC;
@property (strong ,nonatomic) MNDTransferRecordViewController *transferRecordVC;
@property (weak, nonatomic) IBOutlet UIButton *transferConditionButton;
@property (strong,nonatomic) UIButton *moreContentButton;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *progressViewWidth;
@property (weak, nonatomic) IBOutlet UIView *progressBottomView;


@end

@implementation MNDCreditorHRdetailViewController

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    self.menuItemWidth = kScreenWidth*0.25;
    //    self.
    self.menuViewStyle = WMMenuViewStyleLine;
    self.titleSizeSelected = 14.0;
    self.titleSizeNormal = 14.0;
    self.titleColorNormal = [UIColor blackColor];
    self.titleColorSelected = [UIColor colorWithRed:78/255.0 green:140/255.0 blue:238/255.0 alpha:1.0];
    self.menuBGColor = [UIColor whiteColor];
    self.viewTop = HeaderViewHeight + NavigationBarHeight;
    self.viewFrame = CGRectMake(0,HeaderViewHeight + NavigationBarHeight, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
    return self;
}

- (NSArray<NSString *> *)titles {
    return @[@"借款信息",@"出借记录",@"债权信息",@"转让记录"];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.panGesture = [[WMPanGestureRecognizer alloc] initWithTarget:self action:@selector(panOnView:)];
    [self.view addGestureRecognizer:self.panGesture];
    [self loadData];
    [self setupUI];
    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if ([MNDLoginUserModel isUserLogin]) {
        [self loadUserInfos];
    }
}

#pragma mark -加载数据
- (void)loadData {
    [NetworkProgressHUD showHud];
    __weak typeof(self) weakSelf = self;
    NSDictionary *params = [MNDSign signedParamWithDict:@{@"borrow_code":self.borrowCode,@"creditor_code":self.creditorCode}];
    
    [APIManager sendRequestWithPath:API_FINANCE_DETAIL parameters:params method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            [NetworkProgressHUD hideHud];
            
            weakSelf.detaiModel = [MNDFinaceDetailModel mj_objectWithKeyValues:responseModel.data];
            [weakSelf configContents];
        } else {
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)loadUserInfos {
    
    WeakSelf(self);
    [APIManager sendRequestWithPath:API_USER_BASE_INFO
                         parameters:[MNDSign signedParam]
                             method:kXMHTTPMethodGET
                          onSuccess:^(ResponseModel *responseModel) {
                              
                              if (responseModel.status == ResponseSuccess) {
                                  [NetworkProgressHUD hideHud];
                                  weakself.userModel = [MNDUserModel mj_objectWithKeyValues:responseModel.data];
                                  NSLog(@"data: %@", responseModel.data);
                              } else {
                                  NSDictionary *dict = responseModel.msg;
                                  if (dict && dict.count > 0) {
                                      [NetworkProgressHUD showHudMsg:dict[@"error"]];
                                  } else {
                                      [NetworkProgressHUD showHudMsg:@"获取数据失败"];
                                  }
                              }
                              
                          } onFailure:^(NSError *error) {
                              [NetworkProgressHUD showHudNetworkError:error];
                          }];
}

#pragma mark -搭建界面
- (void)setupUI {
    //立即投资按钮
    UIButton *investButton = [[UIButton alloc] init];
    [investButton setTitle:@"确认出借" forState:UIControlStateNormal];
    [investButton setBackgroundImage:[UIImage imageNamed:@"creditor_detail_normal"] forState:UIControlStateNormal];
    [self.view insertSubview:investButton atIndex:100];
    self.investButton = investButton;
    //添加点击事件
    [investButton addTarget:self action:@selector(goInvest:) forControlEvents:UIControlEventTouchUpInside];
    [investButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.bottom.mas_equalTo(self.view);
        make.height.mas_equalTo(44);
    }];
    
    //查看更多按钮
    UIButton *moreContentButton = [[UIButton alloc] init];
    [moreContentButton setTitle:@"向上拖动查看更多信息" forState:UIControlStateNormal];
    [moreContentButton setBackgroundColor:[UIColor colorWithRed:239/255.0 green:239/255.0 blue:244/255.0 alpha:1.0]];
    [moreContentButton setTitleColor:[UIColor colorWithRed:142/255.0 green:142/255.0 blue:142/255.0 alpha:1.0] forState:UIControlStateNormal];
    [moreContentButton setImage:[UIImage imageNamed:@"finance_detail_load_more"] forState:UIControlStateNormal];
    moreContentButton.titleLabel.font = [UIFont systemFontOfSize:13];
    [self.view insertSubview:moreContentButton atIndex:100];
    [moreContentButton addTarget:self action:@selector(clickCheckMore:) forControlEvents:UIControlEventTouchUpInside];
    [moreContentButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.mas_equalTo(self.view);
        make.bottom.mas_equalTo(investButton.mas_top);
        make.height.mas_equalTo(40);
    }];
    self.moreContentButton = moreContentButton;
}

- (void)configContents {
    
    self.borrowTitleLabel.text = self.detaiModel.borrow_title;
    self.borrowYearAprLabel.text = self.detaiModel.borrow_year_apr;
    self.borrowDeadlineLabel.text = [NSString stringWithFormat:@"%@个月",self.detaiModel.creditor_deadline];
    self.leastTenderMoneyLabel.text = [NSString stringWithFormat:@"%zd元起投",self.detaiModel.creditor_least_tender_money.integerValue];
    self.creditorPrincipalLabel.text = [NSString stringWithFormat:@"%@元",self.detaiModel.creditor_principal];
    self.creditorAmountMoneyLabel.text = [NSString stringWithFormat:@"剩余可承接债权%@元",self.detaiModel.creditor_remainingable_money];
    self.creditorWorthLabel.text = [NSString stringWithFormat:@"%@",self.detaiModel.creditor_worth];
    self.borrowMoneyLabel.text = [NSString stringWithFormat:@"%@元",self.detaiModel.borrow_money];
    NSString *progressStr = self.detaiModel.creditor_nowProgress;
    CGFloat number = progressStr.integerValue;
    CGFloat number1 = number/100;
    self.progressViewWidth.constant = self.progressBottomView.bounds.size.width*number1;
    self.backWayLabel.text = self.detaiModel.back_way;
    self.borrowStartDateLabel.text = self.detaiModel.creditor_start_date;
    self.borrowReleaseTimeLabel.text = self.detaiModel.creditor_add_time;
    if (self.detaiModel.borrow_deadline.integerValue > 2) {
        [self.transferConditionButton setTitle:@"满60天后可转" forState:UIControlStateNormal];
    }else {
        [self.transferConditionButton setTitle:@"短期标不可转" forState:UIControlStateNormal];
    }
    if (self.detaiModel.creditor_nowProgress) {
        NSString *progressStr = self.detaiModel.creditor_nowProgress;
        NSInteger number = progressStr.integerValue;
        //        CGFloat number1 = number;
        NSString *progress = [NSString stringWithFormat:@"%ld",(long)number];
        NSString *precent = @"%";
        self.progressLabel.text = [NSString stringWithFormat:@"%@%@",progress,precent];
    }
    
    if ([self.detaiModel.creditor_status isEqualToString:@"1"]) {
        self.investButton.userInteractionEnabled = YES;
        [self.investButton setBackgroundImage:[UIImage imageNamed:@"creditor_detail_normal"] forState:UIControlStateNormal];
    }else {
        self.investButton.userInteractionEnabled = NO;
        [self.investButton setBackgroundImage:nil forState:UIControlStateNormal];
        [self.investButton setBackgroundColor:[UIColor colorWithRed:181/255.0 green:181/255.0 blue:181/255.0 alpha:1.0]];
    }
    
    self.describleVC.brrowContent = self.detaiModel.borrow_content;
    self.describleVC.brrowImg = self.detaiModel.borrow_img;
    self.financeRecordVC.tender = self.detaiModel.tender;
    self.tenderInfoVC.creditor = self.detaiModel.creditor;
    self.transferRecordVC.transfer = self.detaiModel.transfer;
}

//手势滑动
- (void)panOnView:(WMPanGestureRecognizer *)recognizer {
    NSLog(@"pannnnnning received..");
    if (self.topScrollView.frame.origin.y == 0) {
        self.moreContentButton.hidden = NO;
    }else {
        self.moreContentButton.hidden = YES;
    }
    CGPoint currentPoint = [recognizer locationInView:self.view];

    if (recognizer.state == UIGestureRecognizerStateBegan) {
        self.lastPoint = currentPoint;
    } else if (recognizer.state == UIGestureRecognizerStateChanged) {
        
        CGPoint velocity = [recognizer velocityInView:self.view];
        CGFloat targetPoint = velocity.y < 0 ? NavigationBarHeight : NavigationBarHeight + HeaderViewHeight;
        NSTimeInterval duration = fabs((targetPoint - self.viewTop) / velocity.y);
        
        if (fabs(velocity.y) * 1.0 > fabs(targetPoint - self.viewTop)) {
            NSLog(@"velocity: %lf", velocity.y);
            [UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
                self.viewTop = targetPoint;
                self.topScrollView.transform = CGAffineTransformMakeTranslation(0, -(HeaderViewHeight+NavigationBarHeight-self.viewTop));
            } completion:nil];
            
            return;
        }
        
    }
    
    CGFloat yChange = currentPoint.y - self.lastPoint.y;
    self.viewTop += yChange;
    self.topScrollView.transform = CGAffineTransformMakeTranslation(0, -(HeaderViewHeight+NavigationBarHeight-self.viewTop));
    self.lastPoint = currentPoint;
}

- (void)setViewTop:(CGFloat)viewTop {
    
    _viewTop = viewTop;
    
    if (_viewTop <= NavigationBarHeight) {
        _viewTop = NavigationBarHeight;
    }
    
    if (_viewTop > HeaderViewHeight + NavigationBarHeight) {
        _viewTop = HeaderViewHeight + NavigationBarHeight;
    }
    
    self.viewFrame = CGRectMake(0, _viewTop, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
}

#pragma mark -按钮事件
- (void)goInvest:(UIButton *)sender {
    if ([MNDLoginUserModel isUserLogin]) {
        if (self.userModel.userRiskEvaluationState.integerValue == -1) {
            
            [self showRiskAlert];
            return;
        }
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Finance" bundle:[NSBundle mainBundle]];
        MNDCreditorInvestViewController *creditorInvestVC = [storyboard instantiateViewControllerWithIdentifier:[MNDCreditorInvestViewController description]];
        creditorInvestVC.borrowCode = self.detaiModel.borrow_code;
        creditorInvestVC.creditorCode = self.detaiModel.creditor_code;
        [self.navigationController pushViewController:creditorInvestVC animated:YES];
    }else {
        [self goToLoginVC];
    }
}

- (void)clickCheckMore:(UIButton*)sender {
    //    self.scrollView.contentOffset = CGPointMake(0, kScreenHeight) ;
}


#pragma mark -数据源方法
- (NSInteger)numbersOfChildControllersInPageController:(WMPageController *)pageController {
    return self.titles.count;
}

- (UIViewController *)pageController:(WMPageController *)pageController viewControllerAtIndex:(NSInteger)index {
    if (index == 0) {
        UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Finance" bundle:nil];
        MNDFinanceDescribleViewController *describleVC = [storyBoard instantiateViewControllerWithIdentifier:@"MNDFinanceDescribleViewController"];
        describleVC.brrowContent = self.detaiModel.borrow_content;
        self.describleVC = describleVC;
        return describleVC;
    }else if(index == 1){
        UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Finance" bundle:nil];
        MNDFinanceRecordViewController *financeRecordVC = [storyBoard instantiateViewControllerWithIdentifier:@"MNDFinanceRecordViewController"];
        self.financeRecordVC = financeRecordVC;
        financeRecordVC.tender = self.detaiModel.tender;
        return financeRecordVC;
    }else if (index == 2){
        UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Finance" bundle:nil];
        MNDTenderInfoViewController *tenderInfoVC = [storyBoard instantiateViewControllerWithIdentifier:@"MNDTenderInfoViewController"];
        self.tenderInfoVC = tenderInfoVC;
        tenderInfoVC.creditor = self.detaiModel.creditor;
        return tenderInfoVC;
    }else {
        UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Finance" bundle:nil];
        MNDTransferRecordViewController *transferRecordVC = [storyBoard instantiateViewControllerWithIdentifier:@"MNDTransferRecordViewController"];
        transferRecordVC.transfer = self.detaiModel.transfer;
        self.transferRecordVC = transferRecordVC;
        return transferRecordVC;
    }
}

- (IBAction)transferConditionAction:(UIButton *)sender {
    
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    __weak MNDFinanceAlertViewController *alertVC = [storyboard instantiateViewControllerWithIdentifier:@"MNDFinanceAlertViewController"];
    __weak UIView *springView = alertVC.view;
    [KeyWindow addSubview:springView];
    [self addChildViewController:alertVC];
    //        __weak typeof(self) weakSelf = self;
    [alertVC.alertBtn bk_addEventHandler:^(id sender) {
        [UIView animateWithDuration:0.5 animations:^{
            alertVC.alertContainView.frame = CGRectMake(alertVC.alertContainView.frame.origin.x, kScreenHeight, alertVC.alertContainView.frame.size.width, alertVC.alertContainView.frame.size.height);
        } completion:^(BOOL finished) {
            [springView removeFromSuperview];
            [alertVC removeFromParentViewController];
        }];

    } forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark -没有登录，跳转到登录页面

- (void)goToLoginVC {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
    UINavigationController *naviVC = [storyboard instantiateInitialViewController];
    
    [self presentViewController:naviVC animated:YES completion:^{
        
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)showRiskAlert {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您还没有完成[出借用户风险等级测评]，根据金融监管政策要求，用户需要先完成评估才能出借。" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"去测评" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        NSInteger index = [self.navigationController.viewControllers indexOfObject:self];
        
        MNDRiskAssessWebViewController *riskVC = [[MNDRiskAssessWebViewController alloc]init];
        riskVC.webViewUrl = self.userModel.evaluationUrl;
        riskVC.indexOfViewController = index;
        riskVC.title = @"风险测评";
        [self.navigationController pushViewController:riskVC animated:YES];
    }];
    [alert addAction:cancelAction];
    [alert addAction:action];
    
    [self presentViewController:alert animated:YES completion:^{
        
    }];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
